<?php
/**
 * Validador para fazer a valida��o de CPF (Cadastro de Pessoas F�sicas)
 *
 * @package E-mec
 */
class Voitech_Validate_Cpf extends Zend_Validate_Abstract
{
	const INVALID_DIGITS = 'i_number';	
	
	const INVALID_FORMAT = 'i_format';
	
	protected $_messageTemplates = array (
					self::INVALID_DIGITS => "'%value%' is no valid",
					self::INVALID_FORMAT => "Format '%value%' is no valid"
			  );
			  
	private $_pattern = '/(\d{3})\.(\d{3})\.(\d{3})-(\d{2})/i';
	
	private $_skipFormat = false;
	
	/**
	 * Inicializa a inst�ncia do validador
	 *
	 * @param bool $skipFormat fazer valida��o no formato?
	 */
	public function __construct($skipFormat = false) 
	{
		$this->_skipFormat = $skipFormat;
	}
	
	/**
	 * verifica se o cpf � v�lido
	 *
	 * @param string $value cpf a ser validado
	 * @return bool
	 */
	public function isValid( $value ) 
	{		
		$digits = preg_replace('/[^\d]+/i', '', $value);
		if( empty($value) or ( !$this->_skipFormat and !is_numeric( $value ) ) or strlen($digits) != 11 ) 
		{
			$this->_error( self::INVALID_DIGITS );
			return false;
		}
		
		$this->_setValue ( $value );
		
		if( $this->_skipFormat && preg_match( $this->_pattern, $value ) == false ) 
		{
			$this->_error( self::INVALID_FORMAT );
			return false;
		}
		
		
		$firstSum = 0;
		$secondSum = 0;
		
		for($i=0; $i<9; $i++) 
		{
			$firstSum += $digits{$i} * (10 - $i);
			$secondSum += $digits{$i} * (11 - $i);
		}
		
		$firstDigit = 11 - fmod($firstSum, 11);
		
		if($firstDigit >= 10) 
		{
			$firstDigit = 0;
		}
		
		$secondSum = $secondSum + ($firstDigit*2);
		$secondDigit = 11 - fmod($secondSum, 11);
		
		if($secondDigit >= 10)
		{
			$secondDigit = 0;
		}
		
		if(substr($digits, -2) != ($firstDigit . $secondDigit)) 
		{
			$this->_error(self::INVALID_DIGITS);
			return false;
		}
		
		return true;
	}
}


